#!/bin/bash

# 生产环境配置脚本
echo "🏭 APIViewer 生产环境配置向导"
echo "=============================="

# 获取用户输入
read -p "请输入生产环境域名 (例如: api.yourdomain.com): " API_HOST
read -p "请输入API端口 (默认: 443): " API_PORT
API_PORT=${API_PORT:-443}

read -p "使用HTTPS吗? (y/n, 默认: y): " USE_HTTPS
USE_HTTPS=${USE_HTTPS:-y}

if [[ $USE_HTTPS == "y" || $USE_HTTPS == "Y" ]]; then
    PROTOCOL="https"
else
    PROTOCOL="http"
fi

# 创建生产环境变量文件
echo "🔧 创建环境变量文件..."
cat > .env.production << EOF
# APIViewer 生产环境配置
NODE_ENV=production
REACT_APP_API_HOST=${API_HOST}
REACT_APP_API_PORT=${API_PORT}
REACT_APP_API_PROTOCOL=${PROTOCOL}

# 完整API地址
REACT_APP_API_BASE_URL=${PROTOCOL}://${API_HOST}:${API_PORT}
EOF

echo "✅ 环境变量文件已创建: .env.production"

# 创建生产构建脚本
cat > scripts/build-production.sh << 'EOF'
#!/bin/bash
echo "🚀 开始生产环境构建..."

# 检查环境变量文件
if [ ! -f .env.production ]; then
    echo "❌ 找不到 .env.production 文件，请先运行 setup-production.sh"
    exit 1
fi

# 加载环境变量
export $(cat .env.production | xargs)

# 构建应用
echo "📦 正在构建应用..."
npm run build

echo "✅ 构建完成！文件位于 dist/ 目录"
echo "🌐 API配置: ${REACT_APP_API_PROTOCOL}://${REACT_APP_API_HOST}:${REACT_APP_API_PORT}"
EOF

chmod +x scripts/build-production.sh

# 创建 Docker 配置
echo "🐳 创建 Docker 配置..."
cat > Dockerfile.production << EOF
# 多阶段构建
FROM node:18-alpine as build

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .

# 设置生产环境变量
ENV NODE_ENV=production
ENV REACT_APP_API_HOST=${API_HOST}
ENV REACT_APP_API_PORT=${API_PORT}
ENV REACT_APP_API_PROTOCOL=${PROTOCOL}

RUN npm run build

# 生产阶段
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html

# 复制 Nginx 配置
COPY nginx.production.conf /etc/nginx/nginx.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
EOF

# 创建 Nginx 生产配置
cat > nginx.production.conf << EOF
events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    
    # Gzip 压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

    server {
        listen 80;
        server_name _;
        root /usr/share/nginx/html;
        index index.html;

        # 安全头
        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header X-XSS-Protection "1; mode=block" always;

        # 前端路由支持
        location / {
            try_files \$uri \$uri/ /index.html;
        }

        # API 代理到后端
        location /api/ {
            proxy_pass ${PROTOCOL}://${API_HOST}:${API_PORT};
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
            proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto \$scheme;
            
            # 超时设置
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }

        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }

        # 健康检查
        location /health {
            access_log off;
            return 200 "healthy\n";
            add_header Content-Type text/plain;
        }
    }
}
EOF

# 创建 docker-compose 生产配置
cat > docker-compose.production.yml << EOF
version: '3.8'

services:
  frontend:
    build:
      context: .
      dockerfile: Dockerfile.production
    ports:
      - "80:80"
    restart: unless-stopped
    environment:
      - NODE_ENV=production
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  # 如果你的后端也使用 Docker，可以取消注释以下配置
  # backend:
  #   image: your-backend-image:latest
  #   ports:
  #     - "8000:8000"
  #   environment:
  #     - CORS_ORIGINS=${PROTOCOL}://your-frontend-domain.com
  #     - DATABASE_URL=postgresql://...
  #   restart: unless-stopped
EOF

echo ""
echo "🎉 生产环境配置完成！"
echo ""
echo "📁 已创建的文件："
echo "  ├── .env.production              # 环境变量"
echo "  ├── scripts/build-production.sh  # 构建脚本"
echo "  ├── Dockerfile.production        # Docker 配置"
echo "  ├── nginx.production.conf        # Nginx 配置"
echo "  └── docker-compose.production.yml # Docker Compose"
echo ""
echo "🚀 下一步："
echo "1. 构建生产版本:"
echo "   ./scripts/build-production.sh"
echo ""
echo "2. 使用 Docker 部署:"
echo "   docker-compose -f docker-compose.production.yml up -d"
echo ""
echo "3. 或者手动部署 dist/ 目录到你的服务器"
echo ""
echo "⚠️  重要提醒："
echo "- 确保后端已配置 CORS 允许域名: ${PROTOCOL}://your-frontend-domain.com"
echo "- 如果使用 HTTPS，确保已配置 SSL 证书"
echo "- 生产环境建议使用专门的数据库而非开发数据库"
echo ""
echo "📖 详细部署指南请查看: PRODUCTION_DEPLOY.md" 